#coding:utf8
from django.shortcuts import render_to_response
from kgdata import Kgdata


def read_WorkSheet(email, password, sheet_filename, sheet_tb_name):
    try:
        kgdata = Kgdata(email, password)
        kgdata.set_Spreadsheet_File_Key(sheet_filename)
        kgdata.set_wksht_id(sheet_tb_name)
        return kgdata.read_WorkSheet_by_Cells(), ''
    except Exception, e:
        print e
        return None, e


def index(request):

    gLogMail = request.POST.get('gLogMail', '')
    gPsw = request.POST.get('gPsw', '')
    fileName = request.POST.get('gSheetName', '').strip()
    wksht_name = request.POST.get('wksht_name', '').strip()

    wkshtlist, msg = read_WorkSheet(gLogMail, gPsw, fileName, wksht_name)
    print wkshtlist
    if not wkshtlist:
        return render_to_response('msg.html', {'msg': u'读取google数据失败. %s ' % msg, 'url':'/'})

    print wkshtlist

    fck = {'value': r''}

    template_in_database = []
    template = {}
    template['delete'] = 'none'
    template['wksht_name'] = 'Sheet1'

    nRow = 0 #从一行一列开始写数据
    nCol = 0
    try:
        template['smtpSver'] = wkshtlist[nCol + 0][nRow]
        template['logUser'] = wkshtlist[nCol + 1][nRow]
        template['from'] = wkshtlist[nCol + 2][nRow]
        if wkshtlist[nCol + 3][nRow] == u'FALSE':
            template['isSendMyself'] = 'checked="CHECKED"'
        template['mail_list'] = wkshtlist[nCol + 4][nRow]
        template['macro'] = wkshtlist[nCol + 5][nRow]
        template['glogin_mail'] = wkshtlist[nCol + 6][nRow]
        template['gFileName'] = wkshtlist[nCol + 7][nRow]
        template['wksht_name'] = wkshtlist[nCol + 8][nRow]
        template['subject'] = wkshtlist[nCol + 9][nRow]
        fck['value'] = wkshtlist[nCol + 10][nRow]
        template['usedgdata'] = 'checked="CHECKED"'
    except Exception ,e:
        return render_to_response('msg.html', {'msg': u'读取google数据失败.有可能表格式不正确 %s ' % e, 'url':'/'})

    return render_to_response('editmail.html', {'template_in_database': template_in_database,'fck': fck, "template":template})



if __name__ == '__main__':
    pass